package com.lei.study.depth.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.RetryNTimes;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 领导者选举测试
 * </p>
 *
 * @author <a href='mailto:17674030991@163.com'/>伍磊
 */
public class LeaderLatchTest {

    public static void main(String[] args) throws Exception {
        List<CuratorFramework> curatorFrameworkList = new ArrayList<>();
        List<LeaderLatch> leaderLatches = new ArrayList<>();

        // 新建 10个客户端
        for (int i = 0; i < 10; i++) {
            CuratorFramework client = CuratorFrameworkFactory.builder()
                    .connectString("localhost:2181")
                    .connectionTimeoutMs(5000)
                    .sessionTimeoutMs(5000)
                    .retryPolicy(new RetryNTimes(3, 1000))
                    .build();
            curatorFrameworkList.add(client);
            client.start();

            // 领导者选举
            LeaderLatch leaderLatch = new LeaderLatch(client, "/LeaderLatch", "client#" + i);
            leaderLatches.add(leaderLatch);
            leaderLatch.start();
        }

        TimeUnit.SECONDS.sleep(5);

        // 输出当前领导是谁
        for (LeaderLatch leaderLatch : leaderLatches) {
            if (leaderLatch.hasLeadership()) {
                System.out.println("当前Leadership是: " + leaderLatch.getId());
                break;
            }
        }

        System.in.read();

        // 关闭
        System.out.println("开始关闭");
        curatorFrameworkList.forEach(client -> {
            client.close();
        });

    }
}
